//
//  QJNearVC.m
//  QuanJieShopProject
//
//  Created by apple on 2018/1/30.
//  Copyright © 2018年 apple. All rights reserved.
//

#import <BaiduMapAPI_Location/BMKLocationComponent.h>//引入定位功能所有的头文件
#import <BaiduMapAPI_Utils/BMKUtilsComponent.h>
#import <BaiduMapAPI_Map/BMKMapComponent.h>
#import <BaiduMapAPI_Search/BMKSearchComponent.h>

#import "YFNearVC.h"
#import "QJNearVCTCell.h"
#import "QJNearVCHeaderJumpVC.h"
#import "QJNearVCShopDetailVC.h"

//定位
#import <MapKit/MapKit.h>
#import "YFNavigationTopView.h"
#import "QJMineVC.h"
#import "QJCoreScanVC.h"
#import "YFSelectCityView.h"
#import "YFNearVCHeaderView.h"
#import "YFSearchShopViewController.h"
// 顶部跳转
#import "QJCategoryVC.h"
#import "QJHomeVCClassVC.h"

@interface YFNearVC () <UITableViewDelegate,UITableViewDataSource,CLLocationManagerDelegate,BMKLocationServiceDelegate,BMKGeoCodeSearchDelegate>
{
    BMKLocationService* _locService;
    BMKGeoCodeSearch* _geocodesearch;
    CLLocationCoordinate2D _myCoordinate;
    int _page;
    NSString *_locationCity;
    
    // 为什么搞这个属性? 附近排序了,但是城市选择没有排序
    int _showModel; // 显示模式: 0:附近,显示位置  1:选择城市,不显示位置, 默认是0
}
@property (nonatomic, strong) YFNavigationTopView *topView;

@property (nonatomic, strong) UITableView *nearTableView;
@property (nonatomic, strong) YFNearVCHeaderView *headerView;

@property (nonatomic, strong) NSMutableArray *categoryArray;
@property (nonatomic, strong) NSMutableArray *adArray;
@property (nonatomic, strong) NSMutableArray *dataSourceArray;
@property (strong,nonatomic) CLLocationManager* locationManager;

@property (nonatomic, strong) NSString *longitudeStr;//经度
@property (nonatomic, strong) NSString *latitudeStr;//纬度

@property (nonatomic, strong) YFSelectCityView *selectCityView;
@property (nonatomic, strong) CityModel *selectedCityModel;


@end

@implementation YFNearVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupNearUIAction];
    self.longitudeStr = @"";
    self.latitudeStr = @"";
    _page = 1;
    _showModel = 0;
    
    //开始定位
    [self startLocationService];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [self.topView updateCircleImage];
    
    [self setNavAlpha:YES];
    self.navigationController.navigationBarHidden = YES;
   
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self setNavAlpha:NO];
    self.navigationController.navigationBarHidden = NO;
}
#pragma mark -- 界面布局方法
- (void)setupNearUIAction{
    
    kWeakSelf;
    self.headerView = [[YFNearVCHeaderView alloc] init];
    self.headerView.headerBtnClickBlock = ^(NSInteger tag) {  // 十个按钮的点击
        [weakSelf jumpToZeroTagCategoryC:tag];
    };
    self.headerView.adImgViewClickBlock = ^(NearShopModel *model) { // 美食美客
        QJNearVCShopDetailVC *VC = [[QJNearVCShopDetailVC alloc]init];
        VC.shopID = model.id;
        [weakSelf.navigationController pushViewController:VC animated:YES];
    };
    
    
    self.nearTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.topView.frame), UISCREEN_WIDTH, UISCREEN_HEIGHT - self.topView.frame.size.height - Height_TabBar) style:UITableViewStyleGrouped];
    [self.view addSubview:self.nearTableView];
    self.nearTableView.tableHeaderView = self.headerView;
    self.nearTableView.delegate = self;
    self.nearTableView.dataSource = self;
    self.nearTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.nearTableView registerNib:[UINib nibWithNibName:@"QJNearVCTCell" bundle:nil] forCellReuseIdentifier:@"cellID"];
    
    // 刷新
    self.nearTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRefreshNear)];
    self.nearTableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footerRefreshNear)];
    
}

- (void)headerRefreshNear {
    _page = 1;
    [self dataRequestNearAction];
}

- (void)footerRefreshNear {
    _page++; // 失败的话,记得减1
    [self dataRequestNearAction];
}

- (void)headerRefreshSelected {
    _page = 1;
    [self dataRequestSelectedAction];
}

- (void)footerRefreshSelected {
    _page++; // 失败的话,记得减1
    [self dataRequestSelectedAction];
}


#pragma mark -- UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataSourceArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellIdentifier = @"Cell";
    QJNearVCTCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"QJNearVCTCell" owner:self options:nil] lastObject];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    NearShopModel *model = self.dataSourceArray[indexPath.row];
    if (_showModel == 0) {
        cell.cellDistanceLabel.hidden = NO;
    }else {
        cell.cellDistanceLabel.hidden = YES;
    }
    [cell cellUpdateWithModel:model];
    return cell;
}
#pragma mark -- UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 100;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    QJNearVCShopDetailVC *VC = [[QJNearVCShopDetailVC alloc]init];
    NearShopModel *model = self.dataSourceArray[indexPath.row];
    VC.shopID = model.id;
    KPushViewControllerAction(VC);
}

//- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
//    
//    return 300;
//}
#pragma mark -- 数据请求方法
- (void)dataRequestNearAction {  // 请求周边店铺
    
    if (self.longitudeStr.length == 0 || self.latitudeStr.length == 0) {
        [MBPHUD showAlertWithTitle:@"请联网并开启定位..."];
        [self.nearTableView.mj_footer endRefreshing];
        [self.nearTableView.mj_header endRefreshing];
        return;
    }
    
    NSNumber *pageNum = [NSNumber numberWithInt:_page];
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:self.longitudeStr forKey:@"longitude"];
    [dict setObject:self.latitudeStr forKey:@"latitude"];
    [dict setObject:pageNum forKey:@"page"];
    
    
    NSLog(@"附近 dict = %@", dict);
    [WWNetRequest fetchShopListWithParameters:dict success:^(id response) {
        NSLog(@"附近 response = %@", response);
        [self handlerResponse:response];
        
    } failure:^(NSDictionary *error) {
        NSLog(@"附近error = %@", error);

        [self.nearTableView.mj_footer endRefreshing];
        [self.nearTableView.mj_header endRefreshing];
    }];
}

- (void)dataRequestSelectedAction {  // 城市选择接口

    NSNumber *pageNum = [NSNumber numberWithInt:_page];

    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:self.selectedCityModel.code forKey:@"code"];
    [dict setObject:pageNum forKey:@"page"];
    kWeakSelf
    
    NSLog(@"切换城市 dict = %@", dict);

    [WWNetRequest fetchAreacommitWithParameters:dict success:^(id response) {
        
        NSLog(@"切换城市 response = %@", response);
        [weakSelf handlerResponse:response];
        
    } failure:^(NSDictionary *error) {
        NSLog(@"城市编码上传失败");
    }];
}

- (void)handlerResponse:(id)response {
    
    [self.nearTableView.mj_footer endRefreshing];
    [self.nearTableView.mj_header endRefreshing];
    
    if (response) {
        NSArray *adDictArr = response[@"data"][@"topshop"];
        NSArray *shopDictArr = response[@"data"][@"shop"][@"data"];
        
        NSLog(@"adDictArr = %@", adDictArr);
        
        NSMutableArray *adArrTemp = [NSMutableArray array];
        NSMutableArray *shopArrTemp = [NSMutableArray array];
        
        [adDictArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            // 之前用的NearADModel
            NearShopModel *model = [[NearShopModel alloc]initWithDictionary:obj error:nil];
             [adArrTemp addObject:model];
        }];
        
        // 下拉加载无数据提醒
        if (_page != 1 && shopDictArr.count == 0) {
            [MBPHUD showAlertWithTitle:@"已显示全部数据!"];
        }
        
        // 计算距离
        [shopDictArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            NearShopModel *model = [[NearShopModel alloc]initWithDictionary:obj error:nil];
//            NSLog(@"shop_name = %@", model.shop_name);
            // 测试 移动中数据显示
            // 测试 返回后的数据显示
            // 计算距离  确保 userPoint 跟 shopPoint 有经纬度
//            // 测试
//            int i = arc4random_uniform(3);
//            NSLog(@"i = %d", i);
//            if (i == 0) {
//                model.latitude = @"0";
//            }
//            // 测试结束
            
            // 这应该在字典转模型里判断
            model.latitude = [NSString stringWithoutNilFormart:model.latitude];
            model.longitude = [NSString stringWithoutNilFormart:model.longitude];
            // 异常数据直接显示 空
            if ([model.latitude floatValue] < 1) {
                model.latitude = @"";
            }
            if ([model.longitude floatValue] < 1) {
                model.longitude = @"";
            }
//            NSLog(@"latitude = %@", model.latitude);
            
            if (_myCoordinate.latitude != 0 &&_myCoordinate.longitude !=0 && model.latitude.length != 0 && model.longitude.length != 0) {
                BMKMapPoint userPoint = BMKMapPointForCoordinate(_myCoordinate);
                BMKMapPoint shopPoint = BMKMapPointForCoordinate(CLLocationCoordinate2DMake([model.latitude doubleValue],[model.longitude doubleValue]));
                CLLocationDistance distance = BMKMetersBetweenMapPoints(userPoint,shopPoint);
                model.distance = [NSString stringWithFormat:@"%.1f",distance];
            }else {
                model.distance = @"";
            }
//            NSLog(@"距离distance = %@", model.distance);
            [shopArrTemp addObject:model];
        }];
        
        // 距离排序
        [shopArrTemp sortUsingComparator:^NSComparisonResult(NearShopModel *model, NearShopModel *mode2) {
            if ([model.distance floatValue] > [mode2.distance floatValue])
            {
                return NSOrderedDescending;
            }
            else
            {
                return NSOrderedAscending;
            }
        }];
        
        
        // 数据源赋值
        if (_page == 1) {
            // 这里会调用setter方法
            self.dataSourceArray = shopArrTemp;
        }else {
            for (NearShopModel *model in shopArrTemp) {
                [self.dataSourceArray addObject:model];
            }
        }
        
        self.headerView.adArray = [NSArray arrayWithArray:(NSArray *)adArrTemp];

        [self.nearTableView reloadData];
    }
}

#pragma mark -- 百度地图相关
//处理方向变更信息
//- (void)didUpdateUserHeading:(BMKUserLocation *)userLocation
//{
//    KMyLog(@"heading is %@",userLocation.heading);
//}
//处理位置坐标更新
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    NSLog(@"latitude = %f, longitude = %f", userLocation.location.coordinate.latitude, userLocation.location.coordinate.longitude);
    self.longitudeStr = [NSString stringWithFormat:@"%.6f",userLocation.location.coordinate.longitude];
    self.latitudeStr = [NSString stringWithFormat:@"%.6f",userLocation.location.coordinate.latitude];
    
    _myCoordinate = userLocation.location.coordinate;
    
    [_locService stopUserLocationService];
    
    [self saveLocationActionWithLocation:userLocation.location];
    
    [self dataRequestNearAction];
    
    // 是否允许应用访问位置,点击确定后,只调用了 didUpdateBMKUserLocation, 手动反编码
    [self permissionSuccess];
}

/**
 *定位失败后，会调用此函数
 *@param error 错误号
 */
- (void)didFailToLocateUserWithError:(NSError *)error {
    [self dataRequestNearAction];
    [self.topView.leftBtn setTitle:@"未获取" forState:UIControlStateNormal];
}


// 百度地图授权成功
- (void)permissionSuccess {
    //*
    //初始化检索对象
    _geocodesearch = [[BMKGeoCodeSearch alloc]init];
    _geocodesearch.delegate = self;
    //发起反向地理编码检索
    //    CLLocationCoordinate2D pt = (CLLocationCoordinate2D){36.569349, 114.216992};
    BMKReverseGeoCodeOption *reverseGeoCodeSearchOption = [[BMKReverseGeoCodeOption alloc]init];
    reverseGeoCodeSearchOption.reverseGeoPoint = _myCoordinate;
    BOOL flag = [_geocodesearch reverseGeoCode:reverseGeoCodeSearchOption];
    if(flag)
    {
        KMyLog(@"反geo检索发送成功");
    }
    else
    {
        KMyLog(@"反geo检索发送失败");
    }
    //*/
    
}

-(void)onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error
{
    //    KMyLog(@"address = %@, cityCode = %@, city = %@", result.address, result.cityCode, result.addressDetail.city);
    // 定位提醒
    if (![result.cityCode isEqualToString:@"0"] && (result.cityCode.length != 0)) { // 等于0 是无效的回调
        // 去掉"市" 最好判断下 result.addressDetail.city 最后一个字是否为市
        NSRange range = NSMakeRange(result.addressDetail.city.length -1, 1);
        NSString *cityCity = [result.addressDetail.city substringToIndex:result.addressDetail.city.length -1];
        
        [self.topView.leftBtn setTitle:cityCity forState:UIControlStateNormal];

        // 当前城市
        _locationCity = cityCity;
    }
    
}


- (void)startLocationService{

    //初始化BMKLocationService
    _locService = [[BMKLocationService alloc]init];
    _locService.delegate = self;
    _locService.distanceFilter = 50;
    //    _locService.pausesLocationUpdatesAutomatically = NO;
    //    _locService.allowsBackgroundLocationUpdates = YES;
    //启动LocationService
    [_locService startUserLocationService];
}

#pragma mark -- 存储地理位置
- (void)saveLocationActionWithLocation:(CLLocation *)location{
    
    NSString *logStr = [NSString stringWithFormat:@"%.6f",location.coordinate.longitude];
    NSString *latStr = [NSString stringWithFormat:@"%.6f",location.coordinate.latitude];
    
    // 存储本地
    [YFSaveTool userDefaults:logStr key:@"LOG"];
    [YFSaveTool userDefaults:latStr key:@"LAT"];
}

- (void)jumpToVCWithClassID:(NSString *)classID {
    QJNearVCHeaderJumpVC *VC = [[QJNearVCHeaderJumpVC alloc]init];
    VC.classID = classID;
    VC.latitudeStr = self.latitudeStr;
    VC.longitudeStr = self.longitudeStr;
    KPushViewControllerAction(VC);
}

#pragma mark -- 顶部功能按钮点击事件
- (void)jumpToZeroTagCategoryC:(NSInteger)tag {
    // 这里的btnTag是请求参数, 本来应该是后台返回, 但是没有,这里写死,具体看之前的代码

    switch (tag) {
        case YFNearTagFood: // 美食
            [self jumpToVCWithClassID:@"1"];
            break;
        case YFNearTagEntertainment: // 休闲娱乐
            [self jumpToVCWithClassID:@"5"];
            break;
        case YFNearTagFruit:  // 生鲜果蔬
            [self jumpToVCWithClassID:@"4"];
            break;
        case YFNearTagSong: // k歌
            [self jumpToVCWithClassID:@"8"];
            break;
        case YFNearTagHotel: // 酒店
            [self jumpToVCWithClassID:@"9"];
            break;
        case YFNearTagMassage: // 按摩
            [self jumpToVCWithClassID:@"10"];
            break;
        case YFNearTagHair: // 丽人/美发
            [self jumpToVCWithClassID:@"1"];
            break;
        case YFNearTagSnack: // 小吃
            [self jumpToVCWithClassID:@"2"];
            break;
        case YFNearTagSweet: // 甜点
            [self jumpToVCWithClassID:@"1"];
            break;
        case YFNearTagKX:      // 快消
            [self jumpToVCWithClassID:@"6"];
            break;
        default:

            break;
    }
}

#pragma mark -- 懒加载
- (UIView *)topView {
    if (!_topView) {
        
        YFNavigationTopView *topView = [[YFNavigationTopView alloc] initWithFrame:CGRectMake(0, 0, UISCREEN_WIDTH, Height_NavBar)];
        topView.hiddenRightButton = YES;
        _topView = topView;
        kWeakSelf
        topView.rightBtnClick = ^{
            KMyLog(@"个人中心点击");
            QJMineVC *vc= [[QJMineVC alloc] init];
            [weakSelf.navigationController pushViewController:vc animated:YES];
        };
        
        topView.leftBtnClick = ^{ // 定位
            if (weakSelf.selectCityView.isShowing) {
                [weakSelf.selectCityView hidden];
            }else {
                [weakSelf.selectCityView show];
            }
        };
        
        topView.textFieldClick = ^{  // 搜索框

            QJNearVCHeaderJumpVC *VC = [[QJNearVCHeaderJumpVC alloc]init];
            VC.latitudeStr = self.latitudeStr;
            VC.longitudeStr = self.longitudeStr;
            [weakSelf.navigationController pushViewController:VC animated:YES];
        };
        
        topView.codeClick = ^{  // 二维码
            if ([QJUserInfo isLogin]) {
                QJCoreScanVC *VC = [[QJCoreScanVC alloc]init];
                KPushViewControllerAction(VC);
            }else{
                [MBPHUD showAlertWithTitle:@"您还没有登录,请去登录!"];
            }
        };
        
        [self.view addSubview:topView];
        
    }
    return _topView;
}

- (YFSelectCityView *)selectCityView {
    if (!_selectCityView) {
        _selectCityView = [[YFSelectCityView alloc] init];
        kWeakSelf;
        _selectCityView.didSelectRow = ^(CityModel *cityModel) {
            [weakSelf.topView.leftBtn setTitle:cityModel.name forState:UIControlStateNormal];
            
            weakSelf.selectedCityModel = cityModel;
            
            if (_locationCity.length == 0) {
                [MBPHUD showAlertWithTitle:@"城市正在定位中, 请稍后再试!"];
                return;
            }
            
            
            // 选中城市是否为当前城市
            if ([cityModel.name isEqualToString:_locationCity]) {
                // 是  调用附近接口, tableView刷新调用
                _showModel = 0;
                
                // 刷新
                weakSelf.nearTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRefreshNear)];
                weakSelf.nearTableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footerRefreshNear)];
                
                _page = 1;
                [weakSelf dataRequestNearAction];
                
            }else {// 否  调用上传接口,tableView刷新调用
                _showModel = 1;
                // 刷新
                weakSelf.nearTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRefreshSelected)];
                weakSelf.nearTableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footerRefreshSelected)];
                
                _page = 1;
                [weakSelf dataRequestSelectedAction];
                
            }
        };
        
        [self.view addSubview:_selectCityView];
        [self.view bringSubviewToFront:_selectCityView];
    }
    return _selectCityView;
}

- (NSMutableArray *)categoryArray{
    if (!_categoryArray) {
        _categoryArray = [NSMutableArray array];
    }
    return _categoryArray;
}
-(NSMutableArray *)adArray{
    if (!_adArray) {
        _adArray = [NSMutableArray array];
    }
    return _adArray;
}
-(NSMutableArray *)dataSourceArray{
    if (!_dataSourceArray) {
        _dataSourceArray = [NSMutableArray array];
    }
    return _dataSourceArray;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
